<template>
  <div style="height:100%;width:100%;" ref="lineBoxRef" :lineChartData="lineChartData" :xAxisData="xAxisData"></div>
</template>

<script>
import * as echarts from 'echarts';
import { markRaw, nextTick, onMounted, reactive, ref, toRefs, watch } from 'vue';
export default {
  props: {
    lineChartData: {
      type: Array,
      default: []
    },
    xAxisData: {
      type: Array,
      default: []
    },
  },
  setup(props, context) {
    const lineBoxRef = ref(null)
    const state = reactive({
      lineChart: null,
      option: {
        color: [],
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: []
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: []
      },
    })

    watch(() => props.lineChartData, (newVal, oldVal) => {
      if (newVal) {
        init()
      }
    })

    function init() {
      state.lineChart && state.lineChart.dispose()
      const colorData = []
      const legendData = []
      const seriesData = []
      props.lineChartData && props.lineChartData.map(item => {
        colorData.push(item.color)
        legendData.push(item.name)
        seriesData.push(
          {
            name: item.name,
            type: 'line',
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: item.color,
                },
                {
                  offset: 1,
                  color: 'rgb(255, 255, 255)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: item.data,
          },
        )
      })
      state.option.color = colorData
      state.option.legend.data = legendData
      state.option.series = seriesData
      state.option.xAxis[0].data = props.xAxisData || []
      state.lineChart = markRaw(echarts.init(lineBoxRef.value))
      state.lineChart.setOption(state.option)
    }

    onMounted(() => {
    })

    return {
      ...toRefs(state),
      lineBoxRef,
    }
  }
}
</script>

<style>
</style>